<!-- 电子处方 -->
<template>
	<el-container>
		<el-header>
			<NavMenu activeIndex="4" ref="navMenu" />
		</el-header>
		<el-container>
			<el-main>
				<el-affix target=".el-main" :offset="60">
					<el-button v-if="tableEditable" text :icon="CirclePlusFilled" type="primary"
						@click="endEdit">开处方</el-button>
					<el-button v-else text :icon="CirclePlusFilled" @click="startEdit">开处方</el-button>
					<el-button v-if="tableSelectable" text :icon="RemoveFilled" type="danger"
						@click="endRemove">删除行</el-button>
					<el-button v-else text :icon="RemoveFilled" @click="startRemove">删除行</el-button>
					<el-button text :icon="ElementPlus">追加用法费用</el-button>
				</el-affix>
				<div class="paper">
					<div class="paper-header">处方单</div>
					<div class="paper-row">
						<div class="flex-right font-bold" style="flex-basis: 7%;">病人类型：</div>
						<div class="flex-center" style="flex-basis: 13%;">
							<select v-model="feeType">
								<option value="自费">自费</option>
								<option value="公费">公费</option>
								<option value=""></option>
							</select>
						</div>
						<div class="flex-right font-bold" style="flex-basis: 10%;">患者姓名：</div>
						<div class="flex-left font" style="flex-basis: 10%;">{{name}}</div>
						<div class="flex-right font-bold" style="flex-basis: 10%;">患者性别：</div>
						<div class="flex-center" style="flex-basis: 5%;">
							<select v-model="sex" disabled>
								<option value="男">男</option>
								<option value="女">女</option>
								<option value=""></option>
							</select>
						</div>
						<div class="flex-right font-bold" style="flex-basis: 10%;">出生日期：</div>
						<div class="flex-left font" style="flex-basis: 12%;">{{birthday}}</div>
						<div class="flex-right font-bold" style="flex-basis: 13%;">账户余额(￥)：</div>
						<div class="flex-right font" style="flex-basis: 10%; border-bottom: var(--el-border);">
							{{accountBalance}}
						</div>
					</div>
					<div class="frame" style="aspect-ratio: 1 / 1;">
						<div class="table-header-row">
							<div v-if="tableSelectable" class="table-header-cell" style="flex-basis: 3%;" />
							<div class="table-header-cell" style="flex-grow: 1; flex-shrink: 1;">
								<p>项目编号</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 12%;">
								<p>项目名称</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 4%;">
								<p>用量</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 3%;">
								<p>单位</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 3%;">
								<p>频率</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 3%;">
								<p>天数</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 7%;">
								<p>用法</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 3%;">
								<p>滴速</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 4%;">
								<p>单价</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 3%;">
								<p>剂数</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 3%;">
								<p>数量</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 3%;">
								<p>单位</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 7%;">
								<p>金额</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 7%;">
								<p>执行科室</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 3%;">
								<p>皮试</p>
							</div>
							<div class="table-header-cell" style="flex-basis: 5%;">
								<p>结果</p>
							</div>
						</div>
						<div v-for="(row,i) in tableData" class="table-row">
							<div v-if="tableSelectable" class="table-cell"
								style="justify-content: center; flex-basis: 3%;">
								<el-button :icon="Minus" size="small" circle plain type="danger"
									@click="onRemoveRow(row, i)" />
							</div>
							<div class="table-cell" style="flex-grow: 1; flex-shrink: 1;">
								<!-- 项目编号 -->
								<input v-model="row.id" :title="`${row.id}`" disabled />
							</div>
							<div class="table-cell" style="flex-basis: 12%;">
								<!-- 项目名称 -->
								<input v-model="row.name" :title="`${row.name}`" disabled />
							</div>
							<div class="table-cell" style="flex-basis: 4%;">
								<!-- 用量 -->
								<input v-model="row.a" :title="row.a" :disabled="!tableEditable" />
							</div>
							<div class="table-cell" style="flex-basis: 3%;">
								<!-- 单位 -->
								<input v-model="row.a" :title="row.a" :disabled="!tableEditable" />
							</div>
							<div class="table-cell" style="flex-basis: 3%;">
								<!-- 频率 -->
								<input v-model="row.a" :title="row.a" :disabled="!tableEditable" />
							</div>
							<div class="table-cell" style="flex-basis: 3%;">
								<!-- 天数 -->
								<input v-model="row.a" :title="row.a" :disabled="!tableEditable" />
							</div>
							<div class="table-cell" style="flex-basis: 7%;">
								<!-- 用法 -->
								<input v-model="row.a" :title="row.a"
									:disabled="!tableEditable" />
							</div>
							<div class="table-cell" style="flex-basis: 3%;">
								<!-- 滴速 -->
								<input v-model="row.a" :title="row.a" :disabled="!tableEditable" />
							</div>
							<div class="table-cell" style="flex-basis: 4%;">
								<!-- 单价 -->
								<input v-model="row.price" :title="row.price" disabled />
							</div>
							<div class="table-cell" style="flex-basis: 3%;">
								<!-- 剂数 -->
								<input v-model="row.a" :title="row.a" :disabled="!tableEditable" />
							</div>
							<div class="table-cell" style="flex-basis: 3%;">
								<!-- 数量 -->
								<input v-model="row.quantities" :title="row.quantities" :disabled="!tableEditable"
									@input="row.cost = row.price * row.quantities" />
							</div>
							<div class="table-cell" style="flex-basis: 3%;">
								<!-- 单位 -->
								<input v-model="row.specification" :title="row.specification" disabled />
							</div>
							<div class="table-cell" style="flex-basis: 7%;">
								<!-- 金额 -->
								<input v-model="row.cost" :title="row.cost" disabled />
							</div>
							<div class="table-cell" style="flex-basis: 7%;">
								<!-- 执行科室 -->
								<input v-model="row.a" :title="row.a" :disabled="!tableEditable" />
							</div>
							<div class="table-cell" style="flex-basis: 3%;">
								<!-- 皮试 -->
								<input v-model="row.a" :title="row.a" :disabled="!tableEditable" />
							</div>
							<div class="table-cell" style="flex-basis: 5%;">
								<!-- 结果 -->
								<input v-model="row.a" :title="row.a" :disabled="!tableEditable" />
							</div>
						</div>
					</div>
				</div>
			</el-main>
			<el-aside style="border-left: var(--el-border);">
				<Card title="模板">
					<el-row>
						<el-col :span="1" />
						<el-col :span="4" class="flex-center"><el-text>检索：</el-text></el-col>
						<el-col :span="18">
							<el-input v-model="templateRetrievalSearchWord" @input="onTemplateRetrieval" clearable />
						</el-col>
						<el-col :span="1" />
					</el-row>
					<el-tabs type="border-card" style="margin: 5px;" @tab-change="onTemplateRetrievalTabChange">
						<el-tab-pane label="药品" style="height: 200px;">
							<el-table ref="templateRetrievalTableRef" :data="templateRetrievalTableData"
								:max-height="200">
								<el-table-column v-if="tableEditable" width="50" align="center">
									<template #default="scope">
										<el-button :icon="Plus" size="small" circle plain type="primary"
											@click="onAppendRow(scope.row, scope.$index)" />
									</template>
								</el-table-column>
								<el-table-column prop="id" label="编号" show-overflow-tooltip />
								<el-table-column prop="name" label="名称" show-overflow-tooltip />
							</el-table>
						</el-tab-pane>
						<el-tab-pane label="处方">

						</el-tab-pane>
					</el-tabs>
				</Card>
			</el-aside>
		</el-container>
	</el-container>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
	import axiosInstance from '@/Config/axiosConfig'
	import globalStore from '@/store/GlobalStore';
	import Emessage from '@/Utils/Message';
	import { ElMessageBox, ElNotification } from 'element-plus';
	import { CirclePlusFilled, RemoveFilled, ElementPlus, Plus, Minus } from '@element-plus/icons-vue';
	import type { Action, TableInstance } from 'element-plus'
	import '@/pages/doctor/styles/common.scss';
	import '@/pages/doctor/styles/table.scss';
	import { integer2sex, formatDatetime, formatDate } from '@/pages/doctor/scripts/common.ts';
	import NavMenu from '@/pages/doctor/components/NavMenu';
	import Card from '@/pages/doctor/components/Card';

	const docID = uni.getStorageSync('id');
	const doctorCurrentPatient = uni.getStorageSync('doctorCurrentPatient');
	const regID = doctorCurrentPatient.regID;
	const patientID = doctorCurrentPatient.patientID;

	// 电子处方
	const navMenu = ref();
	const feeType = ref('');
	const name = ref('');
	const sex = ref('');
	const birthday = ref('');
	const accountBalance = ref('');
	const tableData = ref([]);
	const tableSelectable = ref(false);
	const tableEditable = ref(true);
	let digID = null;
	let presID = null;

	const getTableData = async () => {
		try {
			const response = await axiosInstance.get('/doc/getPatientDetailById?patientId=' + patientID);
			if (response.status == 200) {
				const p = response.data;
				name.value = p.name;
				sex.value = integer2sex(p.sex);
				birthday.value = formatDate(new Date(p.birthday));
				if (!digID) {
					const response2 = await axiosInstance.get('/doc/getRecordByRegId?regId=' + regID);
					if (response2.status == 200) {
						const d = response2.data;
						if (d) {
							digID = d.id;
						} else {
							ElNotification({ title: '警告', message: '请先完善病历，然后再编写处方。', type: 'warning', duration: 3000 });
						}
					} else {
						ElNotification({ title: response2.status, message: response2.statusText, type: 'error', duration: 3000 });
					}
				}
				if (digID) {
					const response3 = await axiosInstance.get('/doc/getPresByRecordId?recordId=' + digID);
					if (response3.status == 200) {
						const prs = response3.data;
						if (prs) {
							const pr = prs[0];
							const presID = pr.id;
							const rows = pr.medsList.map(x => {
								return {
									id: x.id,
									name: x.name,
									price: x.price,
									quantities: x.quantities,
									specification: x.specification,
									cost: x.price * x.quantities,
								};
							});
							rows.sort((a, b) => {
								return String(a.id).localeCompare(String(b.id));
							});
							tableData.value = rows;
						}
					} else {
						ElNotification({ title: response3.status, message: response3.statusText, type: 'error', duration: 3000 });
					}
				}
			} else {
				ElNotification({ title: response.status, message: response.statusText, type: 'error', duration: 3000 });
			}
		} catch (e) {
			ElNotification({ title: '错误', message: '无法连接服务器！', type: 'error', duration: 3000 });
		}
	};
	
	const saveTableData = async () => {
		if (digID) {
			try {
				const medsList = tableData.value.map(x => {
					return {
						id: x.id,
						quantities: x.quantities,
					};
				});
				const response = await axiosInstance.post('/doc/newPres', {
					doctorId: docID,
					patientId: patientID,
					diagRecordId: digID,
					status: 'NotPaid',
					medsList: medsList,
				});
				if (response.status == 200) {
					const data = response.data;
					ElNotification({ title: '保存', message: '成功保存病人的处方。', type: 'success', duration: 3000 });
				} else {
					ElNotification({ title: response.status, message: response.statusText, type: 'error', duration: 3000 });
				}
			} catch (e) {
				ElNotification({ title: '错误', message: '无法连接服务器！', type: 'error', duration: 3000 });
			}
		} else {
			ElNotification({ title: '警告', message: '请先完善病历，然后再编写处方。', type: 'warning', duration: 3000 });
		}
	};

	const startEdit = () => {
		if (tableSelectable.value)
			endRemove();
		tableEditable.value = true;
	}

	const endEdit = () => {
		tableEditable.value = false;
		saveTableData();
	}

	const startRemove = () => {
		if (tableEditable.value)
			endEdit();
		tableSelectable.value = true;
	}

	const endRemove = () => {
		tableSelectable.value = false;
		saveTableData();
	}

	const onRemoveRow = (row, i) => {
		tableData.value.splice(i, 1);
	};

	const beforeLeavePage = () => {
		// TODO: 离开网页时提醒用户保存
		ElMessageBox.confirm(
			'如果不保存，在上次保存之后所做的更改将会丢失。',
			'保存？',
			{
				confirmButtonText: '保存',
				cancelButtonText: '不保存',
				distinguishCancelAndClose: true,
				type: 'warning',
			}
		).then(() => {
			saveTableData().then(()=>{
				navMenu.value.resumeNavigation();
			});
		}).catch((action: Action) => {
			if (action === 'cancel') {
				navMenu.value.resumeNavigation();
			} else {
				
			}
		});
		return -1;
	};

	getTableData();

	// 模板检索
	const templateRetrievalSearchWord = ref('');
	const templateRetrievalTableRef = ref<TableInstance>();
	const templateRetrievalTableData = [
		{ id: 1, name: '阿莫西林胶囊', price: 15.50, stock: 101, specification: '0.5g*24粒/盒' },
		{ id: 2, name: '布洛芬缓释胶囊', price: 20.00, stock: 80, specification: '0.3g*20粒/盒' },
	];

	const onTemplateRetrieval = (value : string) => {
		Emessage("TODO: 模糊搜索前十条药品", "error");
	};

	const onAppendRow = (row, i) => {
		const index = tableData.value.findIndex(r => r.id == row.id);
		if (index == -1) {
			tableData.value.push({
				id: row.id,
				name: row.name,
				price: row.price,
				quantities: 1,
				specification: row.specification,
				cost: row.price,
			});
		} else {
			tableData.value[index].quantities++;
		}
	};

	const onTemplateRetrievalTabChange = (name : string) => {
		Emessage("TODO: 切换标签页", "error");
	};
</script>

<style lang="scss" scoped>

</style>